package com.emagic.manage.data.network.interceptors;

import android.content.Context;

import com.emagic.manage.data.utils.AndroidUtil;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 请求头中的Cache-Control重写进响应头中的拦截器<br/>
 *
 * @author baoy
 * @version 1.0
 *          Create by 2017/7/1 下午4:05
 */
public class RewriteCacheControlInterceptor implements Interceptor {

    private Context context;

    public RewriteCacheControlInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if(!AndroidUtil.isNetWorkAvailable(context)){//如果没有网络的情况下访问，则只走缓存
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }
        Response originalResponse = chain.proceed(request);
        if (AndroidUtil.isNetWorkAvailable(context)) {
            //有网的时候读接口上的@Headers里的配置
            String cacheControl = request.cacheControl().toString();
            return originalResponse.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build();
        } else {
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                    .removeHeader("Pragma")
                    .build();
        }
    }
}
